package cm.day13.Test3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.*;

class MyRunnable implements Runnable{
private Socket socket;

    public MyRunnable() {
    }

    public MyRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //读取数据
        try {
            BufferedInputStream bis=new BufferedInputStream(socket.getInputStream());
            //文件不重名
            String name = UUID.randomUUID().toString().replace("-", "");
            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("d:/aaa/ddd/"+name+".txt"));
            int len=-1;
            byte[] bytes = new byte[1024];
            while ((len=bis.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
            //回写数据
            OutputStream ops = socket.getOutputStream();
            DataOutputStream dos=new DataOutputStream(ops);
            dos.writeUTF("上传成功");
            dos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}












public class Server {
    public static void main(String[] args) throws IOException {
        //创建线程池
        ThreadPoolExecutor pool=new ThreadPoolExecutor(
                3,
                6,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()

        );
        //创建对象并绑定端口
        ServerSocket ss=new ServerSocket(10086);
        while (true){
            //等待客户端进来
            Socket socket = ss.accept();

            //开启线程
//            new Thread(new MyRunnable(socket)).start();
            pool.submit(new MyRunnable(socket));
        }
    }
}
